<template>
  <div class="page-main">
    <el-breadcrumb class="breadcrumb">
      <el-breadcrumb-item>店主商店</el-breadcrumb-item>
      <el-breadcrumb-item>菜品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="main-content">
      <div class="box-card">
        <span style="color: #101010; font-size: 16px">菜品列表</span>
      </div>
      <div class="box-body">
        <div class="search">
          <div></div>
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="addMealItem">
              添加新菜单
            </el-button>
          </div>
        </div>
        <div class="table">
          <el-table :data="status.mealList" style="width: 100%" v-loading="status.ifLoading">
            <el-table-column type="index" align="center" />
            <el-table-column label="菜品封面" align="center">
              <template #default="scope">
                <img src="https://img.yzcdn.cn/vant/custom-empty-image.png" v-if="scope.row['mealLogo'].length === 0" />
                <img :src="scope.row['mealLogo']" v-else />
              </template>
            </el-table-column>
            <el-table-column prop="mealName" label="菜品名字" align="center" />
            <el-table-column prop="mealPrice" label="菜品价格" align="center" />
            <el-table-column prop="monthlySales" label="月售" align="center" />
            <el-table-column
                fixed="right"
                label="上架"
                align="center"
                width="100"
            >
              <template #default="scope">
                <el-switch @change="changeGround(scope.row)" v-model="scope.row.ifGround" />
              </template>
            </el-table-column>
            <el-table-column
                fixed="right"
                label="操作"
                align="center"
                width="100"
            >
              <template #default="scope">
                <el-button type="text" @click="showDetail(scope.row)">操作</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
  <el-dialog
      v-model="mealDialog.showFlag"
      title="菜品详情"
      width="50%"
      :before-close="closeMealDialog"
  >
    <div>
      <el-form
          label-position="right"
          label-width="120px"
          :model="mealDialog.data"
          :rules="mealDialog.rules"
          ref="mealFormRef"
          :inline="true"
      >
        <el-form-item label="名字:" prop="mealName">
          <el-input v-model="mealDialog.data.mealName" />
        </el-form-item>
        <el-form-item label="价格:" prop="mealPrice">
          <el-input-number v-model="mealDialog.data.mealPrice" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="封面:" class="whole-form">
          <div style="display: flex; flex-wrap: nowrap">
            <img :src="mealDialog.data.mealLogo">
            <el-upload
                ref="upload"
                class="upload-demo"
                :action="jzjUrl + '/uploadMealImage'"
                :headers="header"
                name="file"
                :show-file-list="false"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
            >
              <el-icon class="uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="showConfirm(mealDialog.data.mealName, deleteMealItem)" v-if="mealDialog.data.mealId !== ''">删除</el-button>
        <el-button type="primary" @click="submitMealItem">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <confirm-dialog
      ref="confirmDialogRef"
      :info="info"
      @handleConfirm="handleConfirm"
      @cancelConfirm="cancelConfirm"
  ></confirm-dialog>
</template>

<script setup>
import ConfirmDialog from "@/components/ConfirmDialog";
import {nextTick, onMounted, reactive, ref} from "vue";
import {httpPostManage} from "@/api/httpService";
import {jzjUrl} from "@/api/httpService";
import VueCookies from "vue-cookies";
import {ElMessage} from "element-plus";
import {cutPicture} from "@/tool/manage";
import {Debounce} from "@/tool";

const mealFormRef = ref(null);

const confirmDialogRef = ref(null);

const status = reactive({
  ifLoading: false,
  mealList: []
});

const checkPrice = (rule, value, callback) => {
  if (value <= 0) {
    callback(new Error("请输入有效的价格"));
  } else {
    callback();
  }
};

const mealDialog = reactive({
  showFlag: false,
  data: {
    mealId: "",
    mealName: "",
    mealLogo: "https://img.yzcdn.cn/vant/custom-empty-image.png",
    mealPrice: 0
  },
  rules: {
    mealName: [
      { required: true, message: "请输入菜品名字", trigger: "blur" }
    ],
    mealPrice: [
      { required: true, message: "请输入价格", trigger: "blur" },
      { validator: checkPrice, trigger: 'blur' }
    ]
  }
});

const getShopMealsByToken = async () => {
  status.ifLoading = true;
  let url = "/getShopMealsByToken"
  let res = await httpPostManage(url, {});
  status.mealList = res.data.map(item => {
    item.ifGround = item["grounding"] === 1
    return item
  });
  await nextTick(() => {
    status.ifLoading = false;
  });
};

const addMealItem = () => {
  mealDialog.showFlag = true;
};

const changeGround = async (mealItem) => {
  status.ifLoading = true;
  let url = "/updateGround";
  let params = {
    mealId: mealItem.mealId,
    grounding: mealItem.ifGround ? 1 : 0
  }
  await httpPostManage(url, params);
  ElMessage.success("成功")
  await nextTick(() => {
    status.ifLoading = false;
  });
}

const showDetail = (item) => {
  for (let p in mealDialog.data) {
    mealDialog.data[p] = item[p];
  }
  mealDialog.showFlag = true;
}

const closeMealDialog = () => {
  mealFormRef["value"].resetFields();
  mealDialog.showFlag = false;
  mealDialog.data.mealId = "";
  mealDialog.data.mealName = "";
  mealDialog.data.mealLogo = "https://img.yzcdn.cn/vant/custom-empty-image.png";
  mealDialog.data.mealPrice = 0;
};

const submitMealItem = () => {
  mealFormRef["value"].validate(async (valid) => {
    if (valid) {
      if(mealDialog.data.mealId === "") {
        await doAddMeal();
        await getShopMealsByToken();
        closeMealDialog();
        ElMessage.success("添加成功")
      } else {
        await doUpdateMeal();
        await getShopMealsByToken();
        closeMealDialog();
        ElMessage.success("修改成功")
      }
    }
  });
};

const deleteMealItem = async () => {
  let url = "/deleteMealItem";
  let params = mealDialog.data;
  await httpPostManage(url, params);
  await getShopMealsByToken();
  closeMealDialog();
  ElMessage.success("删除成功")
}

const doAddMeal = async () => {
  let url = "/doAddMeal";
  let params = mealDialog.data;
  await httpPostManage(url, params);
}

const doUpdateMeal = async () => {
  let url = "/doUpdateMeal";
  let params = mealDialog.data;
  await httpPostManage(url, params);
}

/**
 * confirmDialog模块
 **/
const info = reactive({
  title: "",
  content: "",
  methodName: "",
  methodParams: {}
});

const handleConfirm = Debounce(function (dialogInfo) {
  dialogInfo.methodName();
  info.title = "";
  info.content = "";
  info.methodName = "";
  info.methodParams = {};
});

const cancelConfirm = () => {
  info.title = "";
  info.content = "";
  info.methodName = "";
  info.methodParams = {};
  mealDialog.showFlag = true;
};

const showConfirm = Debounce((name, methodName) => {
  mealDialog.showFlag = false;
  info.title = "确定你的操作";
  info.content = "确定要删除" + name +"这一商品吗?";
  info.methodName = methodName;
  confirmDialogRef["value"].makeDialogVisible();
});

/**
 * 上传
 * */
const header = {
  Accept: "application/json;charset=UTF-8",
  tokenMiniAPP: VueCookies.get("tokenWeb") ? VueCookies.get("tokenWeb") : ""
};

const beforeUpload = (rawFile) => {
  //文件格式限制
  let types = ["jpg", "jpeg", "png", "psd"];
  const isImage = types.some((v) => {
    return rawFile.type.includes(v);
  });
  if (!isImage) {
    ElMessage.warning("上传⽂件只支持jpg、jpeg、png、psd格式!");
    return false;
  }

  //文件大小限制
  let size1M = rawFile.size / 1024 / 1024 < 1;
  if (!size1M) {
    ElMessage.warning("上传文件大小不能超过 1MB!");
    return false;
  }
  cutPicture(rawFile, 1, 1);
};

const handleSuccess = (response) => {
  mealDialog.data.mealLogo = jzjUrl + "/images/mealLogo" + response.data;
};

onMounted(async () => {
  await getShopMealsByToken();
})

</script>

<style lang="scss" scoped>
@import "../../assets/style/layout.scss";
.whole-form {
  img {
    width: 178px;
    height: 178px;
    border-radius: 6px;
  }
  .upload-demo {
    width: 178px;
    height: 178px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed black;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-left: 20px;
  }
  .upload-demo:hover {
    border-color: #3894ff;
  }
  .uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
}
</style>